<!DOCTYPE html>
<html lang="zh">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link rel="stylesheet" href="./utils/reset.css" />
    <title>06绘制三角形</title>
  </head>
  <body>
    <canvas id="canvas"></canvas>

    <script type="shader-source" id="vertexShader">
      attribute vec4 triangle_Position;
      void main(){
        gl_Position = triangle_Position;
      }
    </script>
    <script type="shader-source" id="fragmentShader">
      void main(){
        gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);
      }
    </script>

    <script src="./utils/webgl-helper.js"></script>

    <script>
      const canvas = getCanvas("#canvas");
      resizeCanvas(canvas);
      const gl = getContext(canvas);
      const vertexShader = createShaderFromScript(
        gl,
        gl.VERTEX_SHADER,
        "vertexShader"
      );

      const fragmentShader = createShaderFromScript(
        gl,
        gl.FRAGMENT_SHADER,
        "fragmentShader"
      );

      const program = createSimpleProgram(gl, vertexShader, fragmentShader);
      const triangle_Position = gl.getAttribLocation(
        program,
        "triangle_Position"
      );

      const vertices = new Float32Array([0, 0.1, -0.1, -0.1, 0.1, -0.1]);

      // 创建缓冲区
      const vertexBuffer = gl.createBuffer();
      // 将webgl与缓冲区绑定
      gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer);
      // 向缓冲区中写入数据
      gl.bufferData(gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW);
      // 设置顶点属性从缓冲区中读取数据的方式
      gl.vertexAttribPointer(triangle_Position, 2, gl.FLOAT, false, 0, 0);

      gl.enableVertexAttribArray(triangle_Position);

      gl.useProgram(program);
      gl.clearColor(0, 0, 0, 1);
      gl.clear(gl.COLOR_BUFFER_BIT);
      gl.drawArrays(gl.TRIANGLES, 0, 3);
    </script>
  </body>
</html>
